<template>
  <div class="app-container" >
    <div v-if="type === 0 && show === 1">
      <el-row >
        <el-col :span="24">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="100px">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="queryParams.enterpriseName" placeholder="请输入企业名称" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="所属行业" prop="enterpriseAddress">
              <el-select v-model="queryParams.industry" placeholder="请选择所属行业" style="width:150px">
                <el-option v-for="dict in dict.type.customer_industry" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业性质" prop="enterpriseNature">
              <el-select v-model="queryParams.enterpriseNature" placeholder="请选择企业性质" clearable style="width:150px">
                <el-option v-for="dict in dict.type.enterprise_nature" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button type="primary" plain icon="el-icon-edit" size="mini" :disabled="multiple"
                         @click="editBusinessManager">修改业务经理</el-button>
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            </el-form-item>
            <div class="search-row manager-row" v-if="isAdmin==='1'">
              <el-form-item
                size="mini"
                label="电销人员"
                prop="receiveId"
              >
                <div class="manager-tags">
     <span
       v-for="manager in managerList"
       :key="manager.userId"
       :class="['manager-tag', queryParams.receiveId === manager.userId ? 'active' : '']"
       @click="handleManagerSelect(manager)"
     >
        {{ manager.nickName }}
      </span>
                </div>
              </el-form-item>
            </div>
          </el-form>
<!--          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>-->

          <el-dialog :visible.sync="dialogVisiblePdf" append-to-body>
            <pdf v-for="item in pageTotal" :src="pdfUrl" :key="item" :page="item"></pdf>
          </el-dialog>
          <div style="width: 100%;height: 90vh;overflow:auto; margin-bottom: 30%;padding-bottom: 18%;position: relative;">
          <el-table :row-style="{ height: '30px' }" :cell-style="{ padding: '0px' }" height="500" size="mini" border
                    :header-cell-style="{'text-align':'center'}"  v-loading="loading" :data="electricList" @selection-change="handleSelectionChange"
            :row-class-name="tableRowClassName" @row-click="handleCurrentChange" highlight-current-row>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" type="index" :index="indexMethod" />
            <el-table-column label="创建时间" align="center" prop="creationTime" width="100" v-if="columns[10].visible"
              :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="最新操作时间" align="center" prop="creationTime" width="100" v-if="columns[0].visible"
              :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.followTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="最新进展" align="left" prop="lastRecord" :show-overflow-tooltip="true" width="120" />
            <el-table-column label="企业名称" align="left" prop="enterpriseName" width="180" v-if="columns[0].visible"
              :show-overflow-tooltip="true" />
            <el-table-column label="联系人" align="center" prop="contacts" v-if="columns[2].visible" width="70"
              :show-overflow-tooltip="true" />
            <el-table-column label="联系电话" align="center" prop="telephone" v-if="columns[3].visible" width="100"
              :show-overflow-tooltip="true" />
            <el-table-column label="行政区域" align="center" prop="areaName" v-if="columns[4].visible"
              :show-overflow-tooltip="true" />
            <el-table-column label="企业性质" align="center" prop="enterpriseNature" v-if="columns[5].visible"
              :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.enterprise_nature" :value="scope.row.enterpriseNature" />
              </template>
            </el-table-column>
            <el-table-column label="所属行业" align="center" prop="industry" v-if="columns[6].visible" width="160"
              :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.customer_industry" :value="scope.row.industry" />
              </template>
            </el-table-column>
<!--            <el-table-column label="开户银行" align="center" prop="accountBank" v-if="columns[7].visible"-->
<!--              :show-overflow-tooltip="true" />-->
<!--            <el-table-column label="开户账号" align="center" prop="account" v-if="columns[8].visible"-->
<!--                             :show-overflow-tooltip="true" />-->
<!--            <el-table-column label="税务号" align="center" prop="taxId" v-if="columns[9].visible"-->
<!--              :show-overflow-tooltip="true" />-->
            <el-table-column label="成立日期" align="center" prop="establishmentDate" width="100" v-if="columns[9].visible"
              :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.establishmentDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="注册资金" align="center" prop="registeredCapital" v-if="columns[11].visible"
                             :show-overflow-tooltip="true" width="80">
              <template slot-scope="scope">
    <span v-if="scope.row.registeredCapital !== null && scope.row.registeredCapital !== undefined">
      {{scope.row.registeredCapital}}万元
    </span>
                <span v-else>
      {{scope.row.registeredCapital}}
    </span>
              </template>
            </el-table-column>

            <el-table-column label="状态" align="center" prop="status" v-if="columns[12].visible"
              :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.honer_status" :value="scope.row.status" />
              </template>
            </el-table-column>
            <el-table-column label="附件" align="center" prop="businessLicense" v-if="columns[13].visible">
              <template slot-scope="scope">
                <el-button v-if="scope.row.url != null && scope.row.url != ''"  @click.stop="queryUploadFile(scope.row.businessLicense)" size="small"
                  type="text">附件</el-button>
                <el-button size="small" v-else type="text">无附件</el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="100">
              <template slot-scope="scope" v-if="scope.row.isShow === 0">
                <el-button size="mini" type="text" icon="el-icon-edit"
                  @click.stop="handleUpdate(scope.row, scope.$index)" title="修改"></el-button>
                <el-button size="mini" type="text" icon="el-icon-s-promotion"
                  @click.stop="convertBusiness(scope.row)" title="转商机"></el-button>
                <el-button size="mini" type="text" icon="el-icon-tickets" @click="returnEle(scope.row)" title="退回"></el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
          </div>
        </el-col>
      </el-row>
      <el-row>
        <div v-if="open">
          <el-row>
            <el-col :span="24">
              <UpdateEle @change="close" :opt="'select'" :id="id" :index="index" ref="operateref"></UpdateEle>
            </el-col>
          </el-row>
        </div>
      </el-row>
    </div>
    <el-dialog title="修改主分类" :visible.sync="classOpen" width="20%" style="height:1000px">
      <treeselect v-model="classificationIds" :options="options" placeholder="请选择主分类" v-if="opd != 'details'"
        style="width: 202.5px" />
      <el-input v-else v-model="form.label" placeholder="主分类" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitClass">确 定</el-button>
        <el-button @click="classOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
    <div v-if="type === 1">
      <UpdateEle @change="closeEle" :opt="opt" :id="id" :index="index"></UpdateEle>
    </div>
    <div v-if="show == 2">
      <Operate @change="closeEle" :opt="'add'" :business="business" :enterpriseName="enterpriseName"
        :enterpriseId="enterpriseId" :uuid="uuid"></Operate>
    </div>
    <select-user ref="select" :type="userType" :sign="sign" @ok="selectUser"></select-user>
    <!--    附件展示对话框-->
    <el-dialog :visible.sync="ImgDig" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <el-dialog title="查看附件" :visible.sync="openFileList" width="500px" append-to-body>
      <el-table :data="fileList">
        <el-table-column label="文件名称" align="center" prop="fileName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="120">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click.stop="handleView(scope.row)" title="查看"></el-button>
            <el-button size="mini" type="text" icon="el-icon-download"
              @click="handleDownload(scope.row.url, scope.row.fileName)" title="下载"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listElectric, returnEle, updateClass, editBusinessManager, convert, treeElectric,listAllPerson } from "@/api/electric/electric";
import UpdateEle from "./updateEle.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import MainType from "@/components/MainType/index"
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import SelectUser from "../../system/role/selectUser.vue";
import { listType } from "@/api/maintype/type";
import Operate from "../businessinfo/operate.vue";
import Add from "../seas/add.vue";
import { download } from "@/utils/request";
import { queryFile, fileRemove } from "@/api/system/file";
import pdf from "vue-pdf";
export default {
  name: "Electric",
  components: { Add, Treeselect, Operate, UpdateEle, MainType, SelectUser, pdf },
  dicts: ['customer_industry', 'enterprise_nature', 'administrative_area', 'honer_status'],
  data() {
    return {
      uuid: "",
      // 遮罩层
      loading: true,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //传递给商机管理的对象
      business: null,
      pageTotal: null,
      pdfUrl: '',
      fileList: [],
      openFileList: false,
      //传递给商机管理的客户名称和id
      enterpriseName: null,
      managerList:[],
      enterpriseId: null,
      // 总条数
      total: 0,
      ImgDig: false,
      dialogImageUrl: null,
      type: 0,
      dialogImageUrlPdf: '',
      dialogVisiblePdf: false,
      opt: 'add',
      id: '',
      //修改主分类
      classOpen: false,
      userType: '1',
      isAdmin:null,
      sign: '1',
      typeCode: 'ele',
      // 电销管理信息表格数据
      electricList: [],
      show: 1,
      classificationIds: '650c44e1-b575-4b62-9d54-1ba9d1e8abb7',
      //转商机传递的电销id
      electricId: null,
      enterIds: [],
      // 选中数组
      ids: [],
      //是否展示查看
      open: false,
      //树节点数据
      options: null,
      index: null,
      // 表单参数
      form: {},
      // 列信息
      columns: [
        { key: 0, label: `企业名称`, visible: true },
        { key: 2, label: `联系人`, visible: true },
        { key: 3, label: `联系电话`, visible: true },
        { key: 4, label: `行政区域`, visible: true },
        { key: 5, label: `企业性质`, visible: true },
        { key: 6, label: `所属行业`, visible: true },
        { key: 7, label: `开户银行`, visible: true },
        { key: 8, label: `开户账号`, visible: true },
        { key: 9, label: `税务号`, visible: true },
        { key: 10, label: `成立日期`, visible: true },
        { key: 11, label: `创建时间`, visible: true },
        { key: 12, label: `注册资金`, visible: true },
        { key: 13, label: `状态`, visible: true },
        { key: 14, label: `附件`, visible: true },
      ],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        enterpriseName: null,
        enterpriseAddress: null,
        enterpriseNature: null,
        electricType: null,
        classificationId: null,
        receiveId:null
      },
    };
  },
  created() {
    this.isAdmin=this.$store.state.user.info.isAdmin;
    this.getList();
    this.getElectricTree();
    this.listType();
    this.listAllPerson();
  },
  methods: {
    /** 查询电销管理信息列表 */
    getList() {
      this.loading = true;
      listElectric(this.queryParams).then(response => {
        this.electricList = response.rows;
        console.log(response.rows)
        this.total = response.total;
        this.loading = false;
      });
    },
    //查询所有电销人员
    listAllPerson(){
      listAllPerson().then(res=>{
        this.managerList=res;
      })
    },
    // 处理业务经理选择
    handleManagerSelect(manager) {
      if (this.queryParams.receiveId === manager.userId) {
        this.queryParams.receiveId = null; // 再次点击取消选择
      } else {
        this.queryParams.receiveId = manager.userId;
      }
      this.handleQuery(); // 触发搜索
    },
    //退回
    returnEle(row) {
      this.$confirm('此操作将退回到对应公海管理, 是否继续?', '退回', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        returnEle(row.electricId).then(res => {
          if (res.code === 200) {
            this.$message.success("退回成功");
            this.getList();
          } else {
            this.$message.error("退回失败");
            this.getList();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消退回'
        });
      });
    },
    //批量修改业务经理
    selectUser(userId, userName, phone, position,nickName) {
      const params = {
        enterIds: this.ids,
        businessManagerId: userId,
        businessManagerName: nickName
      };
      editBusinessManager(params).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.electricId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    guid() {
      function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
      }
      return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    },
    //取消新增或者编辑
    close(data) {
      if(data===false){
        this.type = 0
        this.show = 1;
        this.open = data;
      }
      this.getList();
    },
    //下载
    handleDownload(fileUrl, fileName) {
      let params = {
        resource: fileUrl
      }
      download("/common/download/resource", params, fileName);
    },
    handleView(row) {
      if (row.url != null && row.url != '' && (row.url).indexOf('.pdf') !== -1) {
        this.handlePictureCardPreviewPdf(row.url);
      } else {
        this.handlePictureCardPreview(row.url);
      }
    },
    handlePictureCardPreviewPdf(url) {
      this.pdfUrl = pdf.createLoadingTask(url)
      // 获取页码
      this.pdfUrl.promise.then(pdf => this.pageTotal = pdf.numPages).catch(error => {
      })
      this.dialogImageUrlPdf = url;
      this.dialogVisiblePdf = true;
    },
    //附件对话框
    handlePictureCardPreview(url) {
      this.dialogImageUrl = url;
      this.ImgDig = true;
    },
    queryUploadFile(id) {
      queryFile(id, 'seas').then(response => {
        this.fileList = response.data;
        console.log(this.fileList)
      });
      this.openFileList = true;
    },
    /** 修改主分类 */
    handleUpdateClass() {
      this.enterIds = this.ids;
      console.log(this.enterIds)
      this.classOpen = true;
      this.listType();
    },
    editBusinessManager() {
      this.$refs.select.show();
    },
    //批量修改主分类
    submitClass() {
      const classVO = {
        enterIds: this.enterIds,
        classId: this.classificationIds
      }
      updateClass(classVO).then(res => {
        this.$message.success(res.msg)
        this.classOpen = false;
        this.getList();
      })
    },
    //展示内容
    closeEle(data) {
      this.type = 0;
      this.show = 1;
      console.log("执行了吗:" + data)
      this.open = data;
      this.getList();

    },
    //获取树节点数据
    listType() {
      listType({ typeCode: 'ele' }).then(res => {
        console.log(res);
        this.options = res.data;
      })
    },
    //树点击事件
    getNode(data, node, obj) {
      console.log(data)
      if (data.parentId != '00000000-0000-0000-0000-000000000000') {
        this.queryParams.classificationId = data.id
      } else {
        this.queryParams.classificationId = null
      }
      this.getList()
    },
    //查看企业详情信息
    openDialog(electricId) {
      this.id = electricId;
      this.opt = "select"
      this.type = 1
      this.title = "查看";
    },
    /** 查询部门下拉树结构 */
    getElectricTree() {
      treeElectric().then(response => {
        console.log(response.data)
        this.deptOptions = this.processTreeData(response.data);
      });
    },

    //序号展示
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    processTreeData(data) {
      return [{
        id: data.id,
        label: data.label,
        children: this.processChildren(data.children),
      }];
    },
    processChildren(children) {
      if (!children || children.length === 0) {
        return [];
      }
      const processedChildren = [];
      children.forEach(child => {
        const processedChild = {
          id: child.id,
          label: child.label,
          children: this.processChildren(child.children),
        };
        processedChildren.push(processedChild);
      });

      return processedChildren;
    },
    //转商机
    convertBusiness(row) {
      this.uuid = this.guid();
      this.electricId = row.electricId;
      convert(this.electricId).then(res => {
        this.business = res.data;
        this.enterpriseName = res.data.enterpriseName;
        this.enterpriseId = res.data.enterpriseId;
        this.businness = res.data;
        this.show = 2;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.open = false;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 15,
        enterpriseName: null,
        enterpriseAddress: null,
        enterpriseNature: null,
        electricType: null
      }
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row, index) {
      this.id = row.electricId;
      this.opt = "edit"
      this.index = index + 1;
      this.type = 1
      this.title = "编辑";
    },
    handleAdd(){
      this.opt = "add"
      this.type = 1
      this.title = "新增";
    },
    //索引初始化到对象
    tableRowClassName({ row, rowIndex }) {
      //把每一行的索引放进row
      row.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + rowIndex + 1;
    },
    handleCurrentChange(row, index, column, event) {
      if (this.open===true){
        this.open=false;
        this.$nextTick(() => {
          this.$refs.operateref.selectActiveName()
        })
        this.id = row.electricId;
        this.opt = 'select';
        this.index = row.index;
        this.type = 0;
        console.log(this.id)
        this.open = true;
      }else {
        this.id = row.electricId;
        this.opt = 'select';
        this.index = row.index;
        this.type = 0;
        console.log(this.id)
        this.open = true;
      }
    },
  },

};
</script>
<style scoped lang="scss">
.no-multiple {

  // 隐藏多选
  ::v-deep .el-table_2_column_20 .is-center .el-table-column--selection .is-leaf .el-table__cell {
    display: none;
  }
}
.manager-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;

  .manager-tag {
    padding: 4px 12px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.3s;

    &:hover {
      border-color: #409EFF;
      color: #409EFF;
    }

    &.active {
      background-color: #409EFF;
      border-color: #409EFF;
      color: #fff;
    }
  }
}
</style>
